<script setup>
import { postAddPost, getPostDetail } from '@/axios/api/posts'
import LfButton from '@/components/commonUI/LfButton.vue'
import LfImageUpload from '@/components/commonUI/LfImageUpload.vue'
import LfInput from '@/components/commonUI/LfInput.vue'
import LfTabs from '@/components/commonUI/LfTabs.vue'
import LfTextArea from '@/components/commonUI/LfTextArea.vue'
import { useLastPostListQuery, useUserPostsQuery, useEditArticleMutation } from '@/composables/usePostDataQuery'
import { useMutation } from '@tanstack/vue-query'
//import '@wangeditor/editor/dist/css/style.css' // 引入 css
import RichTextEditor from './components/RichTextEditor.vue'
import SubmitSelectTopic from './components/SubmitSelectTopic.vue'
import SubmitSuccess from './components/SubmitSuccess.vue'
import { postUploadFile } from '@/axios/api/upload'
import { useAddArticleMutation } from '@/composables/usePostDataQuery'
import { useGlobalStore } from '@/stores/globalStore'
import SubmitSelectDiscuss from './components/SubmitSelectDiscuss.vue'
import VoteSubmit from './components/VoteSubmit.vue'
import { ElSelect, ElOption } from 'element-plus'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import AiEditor from '@/components/aiEditor/aiEditor.vue'
import { decryptUrl } from '@/utils/dataUtils'


// import { onBeforeCreate } from 'vue'
const route = useRoute()

const topicList = [
  { id: 3, name: '文章', type: '3' },
  // { id: 5, name: '问题', type: '5' },
  { id: 1, name: '图文', type: '1' },
  { id: 2, name: '视频', type: '2' },
  { id: 4, name: '投票', type: '4' },
]

// 根据type获取activeIndex的映射
const typeToActiveIndex = {
  1: 1, // 图文
  2: 2, // 视频
  3: 0, // 文章
  4: 3, // 投票
}

const globalStore = useGlobalStore()

const postFilter = computed(() => globalStore.postFilter)

const { refetch: refetchLastPostList } = useLastPostListQuery(postFilter)
const { refetch: refetchUserPosts } = useUserPostsQuery(postFilter)

const addArticleMutate = useAddArticleMutation()
const editArticleMutate = useEditArticleMutation()
const topicId = ref(undefined)
const discussId = ref(undefined)
const selectedDiscussName = ref(undefined)
const selectedTopicName = ref('')
const selectedTopicAvatarUrl = ref('')
const valueHtml = ref('')

const previewVideo = ref(undefined)
const uploadVideo = ref(undefined)

const voteComponentRef = ref(null)

const uploadRef = ref(null)
const coverUploadRef = ref(null)
const activeIndex = ref(0)

const title = ref(undefined)
const content = ref(undefined)

const errorMsg = ref(undefined)

const showSuccess = ref(false)

const questionType = ref(undefined)

const voteInfo = ref(null)
const coverImage = ref(null)

const contentData = ref('')


const questionTypeList = [
  { value: 'general', label: '常规问题' },
  { value: 'urgent', label: '紧急问题' },
  { value: 'suggestion', label: '建议' },
]

// 获取帖子详情
const fetchPostDetail = async () => {
  if (!route.params.id) return

  try {
    const res = await getPostDetail({ queryKey: ['postDetail', route.params.id] })
    if (res.code === 0 && res.result) {
      const postData = res.result
      console.log('postData', postData)

      // 设置activeIndex
      activeIndex.value = typeToActiveIndex[postData.type] || 0

      // 设置主题信息
      topicId.value = postData.topicId

      // 设置讨论信息
      if (postData.discussId) {
        discussId.value = postData.discussId
        selectedDiscussName.value = postData.discussName
      }

      // 设置标题
      title.value = postData.title || ''

      // 根据类型设置内容
      if (postData.type == '1') {
        // 图文类型
        content.value = postData.content || ''
        coverImage.value = postData.media[0] || ''
      } else if (postData.type == '2') {
        // 视频类型
        content.value = postData.content || ''
        // 如果有媒体文件，设置预览
        if (postData.media && postData.media.length > 0) {
          try {
            console.log('原始媒体数据:', postData.media[0])
            const decryptedUrl = decryptUrl(postData.media[0])
            console.log('解密后的URL:', decryptedUrl)

            let vSrc
            // 尝试解析JSON格式的媒体数据
            try {
              const mediaData = JSON.parse(decryptedUrl)
              vSrc = Array.isArray(mediaData) ? mediaData[0] : mediaData
            } catch (e) {
              // 如果不是JSON格式，直接使用解密后的URL
              vSrc = decryptedUrl
            }

            console.log('处理后的视频URL:', vSrc)

            // 设置预览和上传视频
            previewVideo.value = vSrc
            uploadVideo.value = vSrc
          } catch (error) {
            console.error('处理视频资源失败:', error)
            // 如果处理失败，使用默认视频URL（仅用于测试）
            const defaultVideoUrl = 'https://media.insta360.com/static/999ed572050c0e518970399a3c6e2899/shoot%20first%20frame%20later%20PC.mp4'
            previewVideo.value = defaultVideoUrl
            uploadVideo.value = defaultVideoUrl
          }
        }
      } else if (postData.type == '3') {
        // 文章类型
        valueHtml.value = postData.content || ''

        contentData.value = postData.content || ''
        console.log('contentData.value', contentData.value)
        coverImage.value = postData.media[0] || ''
      } else if (postData.type == '4') {
        voteInfo.value = postData.voteInfo
        voteInfo.value.content = postData.content
        voteInfo.value.id = route.params.id
      }

      selectedTopicName.value = postData.topicInfo.topicName
      selectedTopicAvatarUrl.value = postData.topicInfo.coverImage

      console.log('selectedTopicName', selectedTopicName.value)
      console.log('selectedTopicAvatarUrl', selectedTopicAvatarUrl.value)

      // 投票类型的数据会通过VoteSubmit组件内部处理

      ElMessage.success('帖子数据加载成功')
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    ElMessage.error('获取帖子详情失败')
  }
}

console.log('beforeCreate‌', route.params.id)
if (route.params.id) {
  fetchPostDetail()
}
const changeSubmitType = (value) => {
  activeIndex.value = value
}

const handleTopicClick = (id, name) => {
  topicId.value = id
  // 清除讨论
  discussId.value = undefined
  selectedDiscussName.value = undefined
}

const handleDiscussClick = (id, name) => {
  selectedDiscussName.value = name
  discussId.value = id
}

const handleSubmit = () => {
  console.log('activeIndex.value', activeIndex.value)

  if (activeIndex.value == 3) {
    // if (activeIndex.value === 4) {
    voteSubmit()
    return
  }

  if (!verify()) return

  if (activeIndex.value == 0) {
    // 文章：上传封面
    if (coverImage.value) {
      coverUploadRef.value?.uploadImg((res) => {
        articleSubmit(res)
      })
    } else {
      articleSubmit()
    }

  } else if (activeIndex.value === 1) {
    // if (activeIndex.value === 2) {
    // 图文：上传图片
    if (coverImage.value) {
      uploadRef.value?.uploadImg((res) => {
        videoSubmit(res)
      })
    } else {
      videoSubmit()
    }
  } else if (activeIndex.value == 2) {
    // if (activeIndex.value === 3) {
    if (!uploadVideo.value) {
      errorMsg.value = '请上传视频'
      return
    }
    if (Object.prototype.toString.call(uploadVideo.value) === '[object String]') {
      videoSubmit([uploadVideo.value])
    } else if (Object.prototype.toString.call(uploadVideo.value) === '[object File]') {
      uploadFileApi((res) => {
        videoSubmit([res])
      })
    }
  }


}

const verify = () => {
  if (topicId.value == undefined) {
    errorMsg.value = '请选择主题'
    return false
  }
  // if (activeIndex.value === 1 && questionType.value === undefined) {
  //   errorMsg.value = '请选择问题类型'
  //   return false
  // }
  if (!title.value || !title.value.trim()) {
    errorMsg.value = '请输入标题'
    return false
  }
  // 文章/提问页签内容校验
  if (activeIndex.value == 0 && (!valueHtml.value || !valueHtml.value.replace(/<[^>]+>/g, '').trim())) {

    // if ((activeIndex.value === 0 || activeIndex.value === 1) && (!valueHtml.value || !valueHtml.value.replace(/<[^>]+>/g, '').trim())) {
    errorMsg.value = '请输入内容'
    return false
  }
  // 图文页签内容校验
  if (activeIndex.value == 1 && (!content.value || !content.value.trim())) {
    // if (activeIndex.value === 2 && (!content.value || !content.value.trim())) {
    errorMsg.value = '请输入内容'
    return false
  }
  return true
}

const mutation = useMutation({
  mutationFn: (data) => postAddPost(data),
  onSuccess: (res) => {
    if (res.code === 500) {
      return
    }

    submitSuccessCallback()
  },
  onError: (error) => {
    errorMsg.value = error.msg || '提交失败，请重试'
  },
})

const articleSubmit = (resImgs) => {
  console.log('resImgs', resImgs)
  editArticleMutate.mutate(
    {
      title: title.value,
      content: valueHtml.value,
      media: resImgs ? resImgs : undefined,
      topicId: topicId.value,
      type: topicList[activeIndex.value].type,
      discussId: discussId.value,
      questionType: questionType.value,
      id: route.params.id,
    },
    {
      onSuccess: (res) => {
        if (res.code === 500) {
          return
        }

        submitSuccessCallback()
      },
    },
  )
}

const videoSubmit = (resImgs) => {
  console.log('resImgs', resImgs)
  editArticleMutate.mutate(
    {
      title: title.value,
      content: content.value,
      media: resImgs ? resImgs : undefined,
      topicId: topicId.value,
      type: topicList[activeIndex.value].type,
      discussId: discussId.value,
      questionType: questionType.value,
      id: route.params.id,
    },
    {
      onSuccess: (res) => {
        if (res.code === 500) {
          return
        }

        submitSuccessCallback()
      },
    },
  )
}

const postSubmit = (resImgs) => {
  //此处得修改编辑的接口???????
  mutation.mutate({
    title: title.value,
    content: content.value,
    topicId: topicId.value,
    type: topicList[activeIndex.value].type,
    cut: 0,
    media: resImgs,
    discussId: discussId.value,
    questionType: questionType.value,
  })
}

const handleInputChange = (e) => {
  title.value = e.target.value
}

const handleTextAreaChange = (e) => {
  content.value = e.target.value
}

const readAndUploadVideo = (e) => {
  const file = e.target.files[0]
  uploadVideo.value = file

  const reader = new FileReader()

  // 监听文件读取完成事件
  reader.onload = function (event) {
    previewVideo.value = event.target.result // 添加到预览数组
  }

  // 读取文件为Base64字符串
  reader.readAsDataURL(file)
}

const handleUploadVideo = () => {
  const input = document.getElementById('videoUpload')
  input.click()
}

const uploadFileApi = (callback) => {
  const formData = new FormData()
  formData.append('Image', uploadVideo.value)

  postUploadFile(formData).then((res) => {
    // console.log(res)
    if (res.code === 500) {
      return
    }
    callback(res.result)
  })
}

const submitSuccessCallback = () => {
  // 刷新帖子列表
  setTimeout(() => {
    refetchLastPostList()
    refetchUserPosts()
  }, 1000)

  showSuccess.value = true
}

const voteSubmit = () => {
  voteComponentRef.value.submitVote()
}

// 视频错误处理
const handleVideoError = (event) => {
  console.error('视频加载失败:', event.target.error)
  // ElMessage.error('视频加载失败，请检查网络或文件格式')
  previewVideo.value = undefined // 清除预览
  // previewVideo.value = 'https://media.insta360.com/static/999ed572050c0e518970399a3c6e2899/shoot%20first%20frame%20later%20PC.mp4'
  // previewVideo.value = 'https://media.insta360.com/static/999ed572050c0e518970399a3c6e2899/shoot%20first%20frame%20later%20PC.mp4'
}

// 视频加载成功处理
const handleVideoLoaded = () => {
  console.log('视频加载成功')
}
</script>

<template>
  <SubmitSuccess v-if="showSuccess" />
  <div v-else class="p-4 flex flex-col gap-4 max-w-[1400px] mx-auto">
    <div class="flex justify-between">
      <div class="flex gap-6 items-end">
        <div class="text-[28px] font-medium">编辑帖子</div>

        <span v-if="selectedTopicName">
          <SubmitSelectTopic :onTopicClick="handleTopicClick" :selectedTopicName="selectedTopicName"
            :selectedTopicAvatarUrl="selectedTopicAvatarUrl" />
          <!-- v-if="topicId && activeIndex !== 4" -->
        </span>
        <SubmitSelectDiscuss v-if="topicId && activeIndex !== 3" :selectedDiscussName="selectedDiscussName"
          :onDiscussClick="handleDiscussClick" :topicId="topicId" />
      </div>
      <LfButton type="primary" :onClick="handleSubmit" :errorMsg="errorMsg">发布</LfButton>
    </div>

    <LfTabs :isEdit="true" :activeIndex="activeIndex" :tabOptions="topicList" :onTopicClick="changeSubmitType" />

    <!-- 只有提问页签显示问题类型选择 -->

    <!-- 文章 -->
    <template v-if="activeIndex == 0">
      <span v-if="title">
        <LfInput placeholder="标题" :onChange="handleInputChange" :values="title" />
      </span>
      <span v-if="coverImage">
        <LfImageUpload ref="coverUploadRef" :maxCount="1" title="上传封面" :values="coverImage" />
      </span>
      <RichTextEditor v-model="valueHtml" />

    </template>

    <!-- <template v-if="activeIndex === 1">
      <LfInput placeholder="标题" :onChange="handleInputChange" />
      <el-select
      v-model="questionType"
      placeholder="请选择问题类型"
      clearable
      class="w-60 mb-2"
    >
      <el-option
        v-for="item in questionTypeList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
      <RichTextEditor v-model="valueHtml" />
    </template> -->
    <!-- 图文 -->
    <div v-if="activeIndex == 1" class="flex flex-col gap-4">
      <!-- <div v-if="activeIndex === 2" class="flex flex-col gap-4"> -->
      <LfInput placeholder="标题" :onChange="handleInputChange" :values="title" />
      <LfTextArea :onChange="handleTextAreaChange" :modelValue="content" />
      <LfImageUpload ref="uploadRef" :values="coverImage" />
    </div>

    <!-- 视频 -->
    <div v-if="activeIndex == 2" class="flex flex-col gap-4">
      <!-- <div v-if="activeIndex === 3" class="flex flex-col gap-4"> -->
      <LfInput placeholder="标题" :onChange="handleInputChange" :values="title" />
      <LfTextArea :onChange="handleTextAreaChange" :modelValue="content" />
      <div>
        <div @click="handleUploadVideo" class="lf-btn-box px-3">上传视频</div>
        <input type="file" :onchange="readAndUploadVideo" id="videoUpload" accept="video/*" />
      </div>
      <!-- <div v-if="previewVideo" class="mt-4"> -->
      <video :src="previewVideo" controls preload="metadata" class="w-[300px] max-w-full rounded-lg shadow-md"
        @error="handleVideoError" @loadeddata="handleVideoLoaded">
        <!-- <source
          :src="previewVideo" 

            type="video/mp4"> -->
        <!-- preload="metadata" -->

        您的浏览器不支持视频播放。
      </video>
      <!-- <div v-if="previewVideo" class="text-sm text-gray-500 mt-2">
          当前视频: {{ previewVideo }}
        </div> -->
      <!-- </div> -->
    </div>

    <!-- 投票 -->
    <div v-if="activeIndex == 3" class="flex flex-col gap-4">
      <!-- <div v-if="activeIndex === 4" class="flex flex-col gap-4"> -->
      <VoteSubmit ref="voteComponentRef" :topicId="topicId" :isEdit="true" :discussId="discussId" :voteInfo="voteInfo"
        :onSubmitSuccess="submitSuccessCallback" />
    </div>
  </div>
</template>

<style scoped lang="scss"></style>
